<template>
	<view class="main">
		<view class="">
			<alltitleVue :title="title" :url="url" />
		</view>


		<view class="search">
			<image src="../static/home/seach.png" mode=""></image>

			<input v-model="keyword" type="text" class="search-input" @keyup.enter="searchData" @input="searchData"
				placeholder="根据姓名、科室找医生" />
			<view class="icon-del" @click="del" v-if='keyword!=""'>
				<u-icon size="34" name="plus-circle" color="#E6E6E6"></u-icon>
			</view>

			<view class="vertical">
			</view>
			<view @tap="gosearchData" class="search-btn">
				搜索
			</view>
		</view>


		<view class="search-list" v-if="keyword != ''">

			<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
				@scrolltolower="lower" @scroll="scroll">
				<view class="scroll-box" v-if='doctor_list.length>0'>
					<view class="list" v-for="(item,index) in doctor_list" @click="itemHandle(item)">
						<view class="title">
							<image src="../static/home/seach.png" mode=""></image>

							<view class="title-flex">
								<view v-if="item.name" v-html="highlightHospital(item.name, keyword)">
								</view>
								<view v-if="item.title" class="title-text"
									v-html="highlightHospital(item.title, keyword)"></view>
							</view>
						</view>

						<!-- <view class="office">
							{{item.typeActive}}
						</view> -->

					</view>
				</view>
				<view class="box-empty" v-else>
					<u-empty text="未找到相关医生" mode="list"></u-empty>
				</view>
			</scroll-view>
		</view>
		<view class="illness-box">
			<view class="illness-title">
				<view class="">
					历史搜索
				</view>
				<image @click="clearOld" v-if="inputTxt.length != 0" src="../static/assets/lajitong.png" mode="">
				</image>
			</view>
			<view v-if="inputTxt.length === 0" class="no-data">暂无历史</view>
			<view class="scroll-illness" v-else>
				<view class="illness-item" :id="item.letter" v-for="(item, index) in inputTxt" :key="index"
					@tap="oldFindList(item)">
					<view class="box-title">
						{{item.key || item.title}}
					</view>
				</view>
			</view>

		</view>
		<!-- 这里没有做热门搜索,只是做了样式 -->
		<!-- <view class="illness-box">
			<view class="illness-title">
				热门搜索
			</view>
			<view v-if="hotDeptList.length === 0" class="no-data">暂无热搜</view>
			<view class="scroll-illness" v-else>
				<view class="illness-item" :id="item.letter" v-for="(item, index) in hotDeptList" :key="index"
					@click="onRank2Item(item)">
					<view class="box-title">
						{{item.name || item.title}}
					</view>
				</view>
			</view>
		</view> -->


	</view>
</template>

<script>
	import {
		toast,
		getStore,
		setStore,
		removeStore
	} from "@/utils/index";
	import alltitleVue from '../components/alltitle.vue';
	import {
		getSearch,
		getregistration
	} from '../service/api.js'
	export default {
		components: {
			alltitleVue,
		},
		data() {
			return {
				url: "preLoading/search",
				//热门搜索
				hotDeptList: [{
					name: "头痛"
				}],
				//历史搜索
				inputTxt: [],
				//搜索医生
				doctor_list: [
					// 	{
					// 	productName: "我是",
					// 	name: "111111",
					// 	typeActive: "种类"
					// },
				],
				synthesis: [],
				keyword: "",

				location: {
					latitude: null,
					longitude: null,
				},
				timer: null,
				title: "搜索",
				debounceTimer: null // 防抖定时器

			}
		},
		onShow() {
			if (getStore("inputTxt")) {
				this.inputTxt = getStore("inputTxt");
			}
		},
		onLoad() {
			//获取医生等级
			this.getlevel();
			// this.getLocation(); // 获取位置
			// this.startLocationUpdates(); // 启动位置更新
		},
		onUnload() {
			// this.stopLocationUpdates(); // 停止位置更新
		},
		methods: {
			//历史搜索
			oldFindList(item) {
				this.keyword = item.key;
				this.searchData();
			},
			//热门搜索
			onRank2Item(item) {
				this.keyword = item.name;
				this.searchData();
			},
			//搜索字显示红色
			highlightHospital(text, keyword) {
				const regExp = new RegExp(`(${keyword})`, 'gi'); // 创建正则表达式，'gi' 为忽略大小写的全局匹配
				return text.replace(regExp, `<span style="font-weight: bold; color: #CCA566;">$1</span>`);
			},
			gosearchData() {
				if (this.keyword == "") {
					toast("请输入进行搜索")
					return
				}
				uni.navigateTo({
					url: '/integration/searchResults/index?name=' + this.keyword + "&current=0"
				})
			},
			//清空历史记录
			clearOld() {
				this.inputTxt = [];
				removeStore("inputTxt");
			},
			// 添加搜索历史记录
			pushItem() {

				// 判断输入框是否有值
				if (this.keyword != "") {
					if (this.inputTxt.length > 10) {
						this.inputTxt.shift();
					}
					if (this.inputTxt.length == 0) {

						this.inputTxt.push({
							key: this.keyword
						});
					} else {
						for (let i = 0; i < this.inputTxt.length; i++) {
							// 判断是否重复添加
							if (this.keyword == this.inputTxt[i].key) {
								return;
							}
						}
						// 添加进数组
						this.inputTxt.push({
							key: this.keyword
						});
					}
					console.log(this.inputTxt)
					// 将数组存入缓存
					setStore("inputTxt", this.inputTxt);
				}
			},
			// 防抖搜索方法
			searchData() {
				// 如果没有输入关键词，清空 doctor_list 并返回
				if (this.keyword == "") {
					this.doctor_list = [];
					return;
				}

				// 清空 doctor_list
				this.doctor_list = [];


				// 如果上一个定时器还没有执行，清除它
				if (this.debounceTimer) {
					clearTimeout(this.debounceTimer);
				}

				// 设置一个新的定时器，延迟 1 秒后执行搜索
				this.debounceTimer = setTimeout(async () => {
					this.pushItem();
					try {
						let params = {
							name: this.keyword,
						};

						let res = await getSearch(params);
						console.log(res, "这里是什么接口");

						if (res.code == 200) {
							
							this.doctor_list = [
								...this.doctor_list,
								...res.data.doctors.map(doctor => {
									const {
										title,
										...doctorWithoutTitle
									} = doctor; // 解构去掉 title 属性
									return {
										...doctorWithoutTitle,
										typeActive: "医生"
									};
								}),
								...res.data.goods.map(goods => ({
									...goods,
									typeActive: "药品"
								})),
								...res.data.deps.map(dep => ({
									...dep,
									typeActive: "科室"
								}))
							];
							
						}
					} catch (error) {
						toast(error);
					}
				}, 500); // 延迟 0.5 秒后执行搜索
			},
			//请求医生等级
			async getlevel() {
				let res = await getregistration("doctor_level")
				if (res.code == 200) {

					this.synthesis = res.rows;
				}
			},

			//医生详情
			itemHandle(item, type = "") {
				console.log(this.synthesis, "这里是什么")
				switch (item.typeActive) {
					case "医生":
						//这里是将医生等级放入item中，医生等级是请求获取的，医生请求里没有
						item.dictLabel = this.synthesis[item.level].dictLabel;

						uni.navigateTo({
							url: '/integration/searchResults/index?name=' + this.keyword + "&current=1"
						})

						//跳转医生详情页 
						// uni.navigateTo({
						// 	url: `/integration/doctorDetails/index?item=${JSON.stringify(item)}`
						// })


						break;
					case "科室":

						uni.navigateTo({
							url: '/integration/searchResults/index?name=' + this.keyword + "&current=2"
						})
						break;
					case "药品":
						uni.navigateTo({
							url: '/integration/searchResults/index?name=' + this.keyword + "&current=3"
						})



						// uni.navigateTo({
						// 	url: `/integration/productList/index?id=${item.id}`
						// })
						break;
					default:

				}

			},



			//清空输入
			del() {


				this.keyword = "";

				this.searchData();

			},
			getLocation() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						this.location.latitude = res.latitude;
						this.location.longitude = res.longitude;

					},
					fail: (err) => {
						console.error('获取定位失败:', err);
					},
				});
			},
			startLocationUpdates() {
				this.timer = setInterval(() => {
					this.getLocation(); // 定期获取位置
				}, 5000); // 每5秒更新一次
			},
			stopLocationUpdates() {
				if (this.timer) {
					clearInterval(this.timer); // 清除定时器
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		height: 100vh;
		background: #F5F3F0;

		.search {
			width: 654rpx;
			padding: 0 24rpx;
			height: 64rpx;
			background: #fff;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			margin-left: 24rpx;
			display: flex;
			justify-content: space-around;
			align-items: center;

			.icon-del {
				transform: rotate(45deg);
			}

			image {
				width: 28rpx;
				height: 28rpx;
				margin-right: 10rpx;
			}

			input {
				font-size: 24rpx;
				width: 456rpx;
			}

			.vertical {
				height: 25rpx;
				border-left: 1rpx solid;
				margin: 0 20rpx;

			}

			.search-btn {
				font-size: 24rpx;
				color: #4D4D4D;
				width: 72rpx;
				height: 40rpx;
				line-height: 40rpx;
				text-align: center;
				background: #F5F3F0;
				border-radius: 4rpx 4rpx 4rpx 4rpx;
			}
		}
	}

	.search-list {
		position: fixed;
		z-index: 10;
		width: 100%;
		height: calc(100vh - 261rpx);
		top: 261rpx;
		left: 0;
		background: #F5F3F0;


		.scroll-Y {
			height: calc(100vh - 300rpx);
			padding-top: 16rpx;
			border-radius: 16rpx 16rpx 16rpx 16rpx;

			.scroll-box {
				margin: 0 24rpx;
				padding: 0 26rpx;
				background: #fff;
				border-radius: 16rpx;
			}
		}

		.list {

			display: flex;
			justify-content: space-between;
			padding: 24rpx 0;
			border-bottom: 1rpx solid #E6E6E6;


			.title {
				display: flex;
				align-items: center;

				image {
					width: 28rpx;
					height: 28rpx;
					margin-right: 15rpx;
				}
			}

			.office {
				text-align: center;
				padding: 2rpx 5rpx;
				border-radius: 2rpx 2rpx 2rpx 2rpx;
				border: 1rpx solid #E6E6E6;
			}
		}

		.list:last-child {
			border: none;
		}

	}

	.illness-box {
		padding: 40rpx 24rpx 24rpx 24rpx;

		.no-data {
			font-size: 28rpx;
		}

		.illness-title {
			font-weight: 400;
			font-size: 28rpx;
			font-weight: bold;
			display: flex;
			justify-content: space-between;
			align-items: center;

			image {
				width: 28rpx;
				height: 28rpx;
			}
		}

		.scroll-illness {
			display: flex;
			flex-wrap: wrap;
			justify-content: flex-start;

			.illness-item {
				font-size: 24rpx;
				color: #808080;
				margin-top: 16rpx;
				margin-right: 24rpx;
				padding: 0 12rpx;
				line-height: 40rpx;
				height: 40rpx;
				// border-radius: 4rpx 4rpx 4rpx 4rpx;
				// border: 1rpx solid #E6E6E6;
				background: #fff;
			}

		}
	}

	.box-empty {
		height: calc(100vh - 300rpx);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.title-text {
		width: 510rpx;
		white-space: nowrap;
		/* 不换行 */
		overflow: hidden;
		/* 超出部分隐藏 */
		text-overflow: ellipsis;
		/* 超出部分显示省略号 */
	}

	.title-flex {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
</style>